<?php

namespace app\admin\controller;
use \think\Db;
use app\admin\controller\Permissions;
use app\admin\model\App as AppModel;
use app\admin\model\Banben as banbenModel;
use think\Session;

class AppSystem extends Permissions
{
    public function index(){
        $model = new AppModel();
        $post = $this->request->param();
//        if (isset($post['appname']) and !empty($post['appname'])) {
//            $where['appname'] = ['like', '%' . $post['appname'] . '%'];
//        }
        if (isset($post['uid']) and $post['uid'] > 0) {
            $where['uid'] = $post['uid'];
        }

        if (isset($post['appname']) and $post['appname'] > 0) {
            $where['appname'] = $post['appname'];
        }

        if (isset($post['appid']) and $post['appid'] > 0) {
            $where['appid'] = $post['appid'];
        }

        if(isset($post['create_time']) and !empty($post['create_time'])) {
            $min_time = strtotime($post['create_time']);
            $max_time = $min_time + 24 * 60 * 60;
            $where['create_time'] = [['>=',$min_time],['<=',$max_time]];
        }

        $articles = empty($where) ? $model->order('create_time desc')->paginate(20) : $model->where($where)->order('create_time desc')->paginate(20,false,['query'=>$this->request->param()]);

        //$articles = $article->toArray();

        $this->assign('shuju',$articles);
        return $this->fetch();
    }

    public function publish(){
        $id = $this->request->has('id') ? $this->request->param('id', 0) : 0;
        $model = new AppModel();
        if($this->request->isPost()) {
            $post = $this->request->post();
            //验证  唯一规则： 表名，字段名，排除主键值，主键名
            $validate = new \think\Validate([
                ['appico', 'require', '请上传缩略图'],
                ['appname', 'require', '应用名称不能为空'],
                ['appid', 'require', 'APPID不能为空']
            ]);
            //验证部分数据合法性
            if (!$validate->check($post)) {
                $this->error('提交失败：' . $validate->getError());
            }
            $uuid = self::uuid(10);
            $data = array("uid"=>$uuid,"appico"=>$post['appico'],"appname"=>$post['appname'],"appid"=>$post['appid'],"create_time"=>time());
            if(false == $model->save($data)) {
                return $this->error('添加失败');
            } else {
                //addlog($model->id);//写入日志
                return $this->success('添加成功','admin/app_system/index');
            }
        }
    }

    public function editorapp(){
        $id = $this->request->has('id') ? $this->request->param('id', 0) : 0;
        $model = new AppModel();
        if($this->request->isPost()) {
            $post = $this->request->post();
            //验证  唯一规则： 表名，字段名，排除主键值，主键名
            $validate = new \think\Validate([
                ['appico', 'require', '请上传缩略图'],
                ['appname', 'require', '应用名称不能为空'],
                ['appid', 'require', 'APPID不能为空']
            ]);
            //验证部分数据合法性
            if (!$validate->check($post)) {
                $this->error('提交失败：' . $validate->getError());
            }
            $uid = $post['uid'];
            if(false == Db::name('app')->where('uid',$uid)->update($post)) {
                return $this->error('编辑失败');
            } else {
                //addlog($model->id);//写入日志
                return $this->success('编辑成功','admin/app_system/index');
            }
        }else{
            $post = $this->request->get();
            $id = $post['id'];
            $data = Db::name('app')->where('uid',$id)->find();
            $list = Db::name('banben')->where('appid',$id)->select();
            $this->assign('data',$data);
            $this->assign('list',$list);
            return $this->fetch();
        }
    }

    public function appdelete(){
        $post = $this->request->get();
        $ver = Db::name('banben')->where('appid',$post['id'])->delete(true);
        $app = Db::name('app')->where('uid',$post['id'])->delete(true);
        if(false == $app){
            return $this->error('删除失败');
        }else{
            return $this->success('删除成功');
        }
    }

    public function verdelete(){
        $post = $this->request->get();
        $ver = Db::name('banben')->where('id',$post['id'])->delete(true);
        if(false == $ver){
            return $this->error('删除失败');
        }else{
            return $this->success('删除成功');
        }
    }

    public function appVersion(){
        $post = $this->request->param();
        $data = Db::name('banben')->where('appid',$post['id'])->select();
        foreach ($data as $key => $value) {
            if($data[$key]['mandatory'] == 'true'){
                $data[$key]['mandatorys'] = "是";
            }else{
                $data[$key]['mandatorys'] = "否";
            }
        }
        $this->assign('usid',$post['id']);
        $this->assign('shuju',$data);
        return $this->fetch();
    }

    public function vsadd(){
        $model = new BanbenModel();
        if($this->request->isPost()) {
            $post = $this->request->post();
            //验证  唯一规则： 表名，字段名，排除主键值，主键名
            $validate = new \think\Validate([
                ['appid', 'require', 'APPid不能为空'],
                ['appversion', 'require', '版本不能为空'],
                ['version_release', 'require', '描述不能为空'],
                ['mandatory', 'require', '请选择是否强制更新']
            ]);
            //验证部分数据合法性
            if (!$validate->check($post)) {
                $this->error('提交失败：' . $validate->getError());
            }
            //$data = array("uid"=>$uuid,"appico"=>$post['appico'],"appname"=>$post['appname'],"appid"=>$post['appid'],"create_time"=>time());
            if(false == $model->save($post)) {
                return $this->error('添加失败');
            } else {
                //addlog($model->id);//写入日志
                return $this->success('添加成功','admin/app_system/index');
            }
        }
        $post = $this->request->param();
        $this->assign('usid',$post['id']);
        return $this->fetch();
    }

    public function ediviosn(){
        $id = $this->request->has('id') ? $this->request->param('id', 0) : 0;
        $model = new BanbenModel();
        if($id > 0){
            if($this->request->isPost()) {
                $post = $this->request->post();
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['appid', 'require', 'APPid不能为空'],
                    ['appversion', 'require', '版本不能为空'],
                    ['version_release', 'require', '描述不能为空'],
                    ['mandatory', 'require', '请选择是否强制更新']
                ]);
                //验证部分数据合法性
                if (!$validate->check($post)) {
                    $this->error('提交失败：' . $validate->getError());
                }
                //$data = array("uid"=>$uuid,"appico"=>$post['appico'],"appname"=>$post['appname'],"appid"=>$post['appid'],"create_time"=>time());
                if(false == $model->save($post,['id'=>$id])) {
                    return $this->error('编辑失败');
                } else {
                    //addlog($model->id);//写入日志
                    return $this->success('编辑成功');
                }
            }else{
                $post = $this->request->param();
                $data = Db::name('banben')->where('id',$post['id'])->find();
                $this->assign('data',$data);
                $this->assign('usid',$post['id']);
                return $this->fetch();
            }
        }
    }

    public static function uuid($length = 10){
        $seed = mt_rand(0, 2147483647) . '#' . mt_rand(0, 2147483647);

        // Hash the seed and convert to a byte array
        $val = md5($seed, true);
        $byte = array_values(unpack('C16', $val));

        // extract fields from byte array
        $tLo = ($byte[0] << 24) | ($byte[1] << 16) | ($byte[2] << 8) | $byte[3];
        $tMi = ($byte[4] << 8) | $byte[5];
        $tHi = ($byte[6] << 8) | $byte[7];
        $csLo = $byte[9];
        $csHi = $byte[8] & 0x3f | (1 << 7);

        // correct byte order for big edian architecture
        if (pack('L', 0x6162797A) == pack('N', 0x6162797A)) {
            $tLo = (($tLo & 0x000000ff) << 24) | (($tLo & 0x0000ff00) << 8)
                | (($tLo & 0x00ff0000) >> 8) | (($tLo & 0xff000000) >> 24);
            $tMi = (($tMi & 0x00ff) << 8) | (($tMi & 0xff00) >> 8);
            $tHi = (($tHi & 0x00ff) << 8) | (($tHi & 0xff00) >> 8);
        }

        // apply version number
        $tHi &= 0x0fff;
        $tHi |= (3 << 12);

        // cast to string
        $uuid = sprintf(
            '%08x%04x%04x%02x%02x%02x%02x%02x%02x%02x%02x',
            $tLo,
            $tMi,
            $tHi,
            $csHi,
            $csLo,
            $byte[10],
            $byte[11],
            $byte[12],
            $byte[13],
            $byte[14],
            $byte[15]
        );

        $str = strtoupper($uuid);
        while (1){
            $uuid = substr(str_shuffle(str_repeat($str, $length)), 0, $length);
            if(!is_numeric($uuid)){
                break;
            }
        }

        return $uuid;
    }
}